<?php

namespace iBrand\Shop\Core\Repositories\Eloquent;

use iBrand\Shop\Core\Models\Clerk;
use iBrand\Shop\Core\Repositories\ClerkRepository;
use Illuminate\Support\Str;
use Prettus\Repository\Eloquent\BaseRepository;


class ClerkRepositoryEloquent extends BaseRepository implements ClerkRepository
{

    const OPEN = 1;
    const CLOSE = 0;

    /**
     * Specify Model class name
     *
     * @return string
     */
    public function model()
    {
        return Clerk::class;
    }

    /**
     * Get a user by the given credentials.
     *
     * @param array $credentials
     *
     * @return mixed
     */
    public function getClerkByCredentials(array $credentials)
    {
        $query = $this->model;

        foreach ($credentials as $key => $value) {
            if (!Str::contains($key, 'password') and !empty($value)) {
                $query = $query->where($key, $value);
            }
        }

        return $query->with('shops')->first();
    }

    /**
     * 获取门店店员信息列表
     * @param $where
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model[]
     */
    public function getClerkList($where)
    {
        return $this->model
            ->with('shops')
            ->where(function ($query) use ($where) {
                if (is_array($where)) {
                    foreach ($where as $key => $value) {
                        if (is_array($value)) {
                            list($operate, $va) = $value;
                            $query = $query->Where($key, $operate, $va);
                        } else {
                            $query = $query->where($key, $value);
                        }
                    }
                }
                return $query->orderBy('is_clerk_owner', 'desc');
            })->get();
    }



    public function getListClerks($where, $shop_name = null)
    {
        return $this->model
            ->with('shops')
            ->whereHas('shops', function ($query) use ($shop_name) {
                if ($shop_name) {
                    return $query->where('name', 'like', '%' . $shop_name . '%');
                }
                return $query;
            })
            ->where(function ($query) use ($where) {
                if (is_array($where)) {
                    foreach ($where as $key => $value) {
                        if (is_array($value)) {
                            list($operate, $va) = $value;
                            $query = $query->Where($key, $operate, $va);
                        } else {
                            $query = $query->where($key, $value);
                        }
                    }
                }
                return $query->orderBy('created_at', 'desc');
            })->paginate(15);
    }

}
